<?php

namespace App\user\service;

use app\model\UserAssetModel;
use app\model\UserModel;
use app\model\UserTokenModel;
use App\user\cache\UserCache;
use App\user\cache\UserTokenCache;
use App\validate\UserValidate;
use \support\Db;

class UserService
{
    static $validate = null;
    // 注册
    public static function register($param) {
        $param['nickname'] = '用户#'.time();
        $param['invite'] = self::getInviteCode();

        Db::beginTransaction();
        try {
            // 创建用户信息
            $user = UserModel::createInfo($param);
            // 生成资产表
            UserAssetModel::createInfo(['user_id' => $user->id]);
            Db::commit();
            return result(OK);
        } catch (\Exception $e) {
            Db::rollBack();
            return result(NO, $e->getMessage());
        }
    }

    // 登陆
    public static function login($param) {
        $where = [];
        if (isset($param['mobile']) && !empty($param['mobile'])) {
            $where = ['mobile' => $param['mobile']];
        } else {
            $where = ['email' => $param['email']];
        }
        $info = UserModel::getInfoByWhere($where, '*');
        $token = uuid();
        // 写入token表
        try {
            UserTokenModel::createInfo([
                'user_id' => $info->id,
                'token' => $token,
                'ip' => $param['ip']
            ]);
        } catch (\Exception $e) {
            return result(NO, $e->getMessage());
        }

        // 写入缓存
        UserTokenCache::set($token, $info, 7*24*3600);

        return result(OK, '登陆成功', compact('token', 'info'));
    }

    // 退出登陆
    public static function logout($param) {
        $info = isToken($param['token']);
        if (empty($info)) return result(NO, '登陆状态有误，请刷新页面后重试！');
        try {
            UserTokenModel::deleteInfo($info['id'], $param['token']);
        } catch (\Exception $e) {
            return result(NO, $e->getMessage());
        }

        UserTokenCache::del($param['token']);
        return result(OK);
    }

    // 注销账号
    public static function writeOff($param) {
        $info = isToken($param['token']);
        Db::beginTransaction();
        try {
            UserModel::updateInfo(['id' => $info['id']], ['status' => UserModel::WRITE_OFF]);
            UserTokenModel::deleteToken($info['id']);
            DB::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            return result(NO,$e->getMessage());
        }
        return result(OK, '账号注销成功！');
    }

    // 编辑信息
    public static function editInfo($param) {
        $info = isToken($param['token']);
        unset($param['token']);
        try {
            UserModel::updateInfo(['id' => $info['id']], $param);
        } catch (\Exception $e) {
            return result(NO,$e->getMessage());
        }
        $info = userModel::getInfoById($info['id']);
        UserTokenModel::updateToken($info['id'], $info);
        return result(OK, '信息修改成功！');
    }

    // 发送验证码
    public static function sendCode($mobile) {
        $res = UserCache::getTime($mobile);
        if (!$res) return result(NO, '系统繁忙，请稍后再试~');
        $code = getRandom(6);
        $res = UserCache::set($mobile, $code, 10*60);
        if ($res) return result(OK, '操作成功', $code);
        return result(NO, '验证码发送失败,请稍后再试!');
    }

    // 获取验证码
    public static function getCode($mobile) {
        $code = UserCache::get($mobile);
        if ($code) return result(OK, '操作成功', $code);
        return result(NO, '验证码不存在!');
    }

    // 生成邀请码
    public static function getInviteCode() {
        $code = getRandom(6, 'invite');
        $info = UserModel::getInfoByWhere(['invite' => $code], 'id');
        while(!empty($info)) {
            $code = getRandom(6, 'invite');
            $info = UserModel::getInfoByWhere(['invite' => $code], 'id');
        }

        return $code;
    }

    // 校验数据
    public static function validates($data, $scene) {
        if (!self::$validate) {
            self::$validate = new UserValidate();
        }
        $res = self::$validate->scene($scene)->check($data);
        if (!$res) {
            return result(NO, self::$validate->getError());
        }
        return result(OK);
    }
}